package com.example.demo_news.service.User;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.persistence.Tuple;
import javax.servlet.http.HttpServletRequest;

import com.example.demo_news.Repository.NewsPhotoRepository;
import com.example.demo_news.Repository.NewsRepository;
import com.example.demo_news.Repository.OfficialRepository;
import com.example.demo_news.entity.MyUser;
import com.example.demo_news.entity.News;
import com.example.demo_news.entity.NewsPhoto;
import com.example.demo_news.entity.OfficialAccount;
import com.example.demo_news.until.*;

import org.hibernate.annotations.SourceType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties.Sort;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Service
public class OfficialAccountService {
    @Autowired
    private UserUntil userUntil;
    @Autowired
    private NewsRepository newsRepository;
    @Autowired
    private OfficialRepository officialRepository;

    // 返回当前账号发布的新闻
    public boolean findNewsByofficialAccountId(Model model, Integer page) {
        MyUser user = userUntil.getUser();
        List<News> newsList =
        newsRepository.findNewsByofficialAccountId(user.getOfficialAccount().getId());
        model.addAttribute("newsList", newsList);
        // Page<News> pageData = newsRepository.findAll(PageRequest.of(page-1, 10));
        // // 获取第page页的共十条记录     
        // List<News> newsList = pageData.getContent();
        // model.addAttribute("newsList", newsList);
        //  // 获得当前页面的记录
        // // 获得总记录数
        // model.addAttribute("totalCount", pageData.getTotalElements());
        // // 获得总页数
        // model.addAttribute("totalPage", pageData.getTotalPages());
        return true;
    }
    //返回新闻的详细信息
    public boolean findNewsById(Integer id,Model model){
        News news=newsRepository.findNewsById(id);
        model.addAttribute("news", news);
        return true;
    }

    // 保存新闻
    public boolean save(News news, HttpServletRequest request) {
        // 取出当前会话对象
        MyUser user = userUntil.getUser();
        OfficialAccount officialAccount = user.getOfficialAccount();
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = mRequest.getFiles("file");
        Iterator<MultipartFile> iter = files.iterator();
        while (iter.hasNext()) {
            MultipartFile file = iter.next();// 取出每一个上传文件
            try {
                news.setPhoto(this.saveFile(file));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            Date date = new Date();
            news.setDate(date);
            news.setOfficialAccountId(officialAccount.getId());
            // 保存新闻
            newsRepository.save(news);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // 返回新闻号信息
    public boolean myOfficialMessage(Model model) {
        MyUser user = userUntil.getUser();
        OfficialAccount OfficialAccount = user.getOfficialAccount();
        model.addAttribute("official", OfficialAccount);
        return true;
    }

    // 修改新闻号信息
    public boolean modifyOfficial(OfficialAccount officialAccount, MultipartFile photo) throws Exception {
        try {
            MyUser user = userUntil.getUser();
            officialAccount.setUser(user);
            officialAccount.setPhoto(this.saveFile(photo));
            officialAccount.setId(user.getOfficialAccount().getId());
            // 保存图片,返回路径
            officialRepository.save(officialAccount);

            return true;
        } catch (Exception e) {
            return false;
        }

    }
    //删除发布的新闻
    public boolean deleteNewsDetail(Integer id){
        newsRepository.delete(newsRepository.findNewsById(id));
        return true;
    }



    public String saveFile(MultipartFile file) throws Exception {
        String path = "nothing";
        if (file != null) {
            if (file.getSize() > 0) {
                
                String fileName = UUID.randomUUID() + "."  + file.getContentType().substring(file.getContentType().lastIndexOf("/") + 1);
                // 创建文件名称
                // path=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getServletContext().getRealPath("/")+fileName;
                // path = ResourceUtils.getURL("classpath:").getPath() + "static/images/" + fileName;
                path="D:/Code/springboot/demo_news/src/main/resources/static/images/"+fileName;
                File saveFile = new File(path);
                file.transferTo(saveFile);
                path=fileName;//返回文件名
            }
        }
        return path;
    }
}
